package org.example.admin.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.example.admin.dto.UserAuthInfoDto;
import org.example.admin.dto.UserRoleListDto;
import org.example.common.utils.CommonUtil;
import org.example.common.utils.DateTimeUtil;
import org.example.db.entity.Role;
import org.example.db.entity.RolePermission;
import org.example.db.entity.User;
import org.example.db.mapper.UserMapper;
import org.example.security.service.UserRoleService;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.LinkedList;
import java.util.List;

@Service
public class AdminUserService {

    UserMapper userMapper;
    PasswordEncoder passwordEncoder;
    UserRoleService userRoleService;

    public AdminUserService(UserMapper userMapper, PasswordEncoder passwordEncoder, UserRoleService userRoleService) {
        this.userMapper = userMapper;
        this.passwordEncoder = passwordEncoder;
        this.userRoleService = userRoleService;
    }

    public void addUser(User user){

        // 使用mybatis-plus的id自动生成策略
        user.setId(null);

        //
        user.setPassword(passwordEncoder.encode(user.getPassword()));

        String time = DateTimeUtil.getDateTimeString(LocalDateTime.now());
        user.setAddTime(time);
        user.setUpdateTime(time);

        user.setLastLoginIp(null);
        user.setLastLoginTime(null);

        int count = userMapper.insert(user);
        CommonUtil.isSqlExcute(count);
    }

    public Long getUserId(){

        UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        // TODO 使用缓存

        return userMapper.selectList(
                new QueryWrapper<User>().lambda().eq(User::getUsername, userDetails.getUsername())).get(0).getId();
    }

    @Transactional
    public UserAuthInfoDto getUserAuthInfo(){

        UserAuthInfoDto userAuthInfoDto = new UserAuthInfoDto();

        Long userId = this.getUserId();

        LinkedList<String> roles = new LinkedList<>();
        for(Role role: userRoleService.getRolesByUserId(userId)){
            roles.add(role.getName());
        }
        User user = userMapper.selectById(userId);

        userAuthInfoDto.setRoles(roles);
        userAuthInfoDto.setAvatar(user.getAvatar());
        userAuthInfoDto.setNickname(user.getNickname());
        return userAuthInfoDto;
    }

    /**
     *
     * @return 管理员列表
     */
    @Transactional
    public List<UserRoleListDto> getAdminUserList(){

        List<UserRoleListDto> userRoleListDtos = new LinkedList<UserRoleListDto>();
        for (User user:userMapper.selectList(null)) {
            UserRoleListDto userRoleListDto = new UserRoleListDto();
            userRoleListDto.setUser(user);
            userRoleListDto.setRoleList(userRoleService.getRolesByUserId(user.getId()));
            userRoleListDtos.add(userRoleListDto);
        }
        return userRoleListDtos;
    }

    public void deleteRoleById(Long UserId){
        userRoleService.deleteRolesById(UserId);
    }

    public void addRoleUser(Long userId,Long roleId){
        userRoleService.addUserRole(userId,roleId);
    }

    public void updateUser(User user){

        String password  = userMapper.selectById(user.getId()).getPassword();
        if(!password.equals(user.getPassword())){
            user.setPassword(passwordEncoder.encode(user.getPassword()));
        }
        userMapper.update(user,new QueryWrapper<User>().
                lambda().eq(User::getId, user.getId()));
    }

    public void deleteUser(Long userId){
        userMapper.deleteById(userId);
    }


}
